package com.douyu.data.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
//    @Autowired
//    private ValueOperations kVOperator;

    public void KVSet(String key, String value){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 通过重载的方式实现过期以及替换的操作
        valueOperations.set(key, value);
        System.out.println(key+": " + value);
    }

    public String KVGet(String key){
        // 通过重载的方式实现过期以及替换的操作
        Object o = redisTemplate.opsForValue().get(key);
        System.out.println(key+": " + o);
        return o.toString();
    }
    
    public void transactional(){
        redisTemplate.execute(new SessionCallback<Object>() {
            @Override
            public <K, V> Object execute(RedisOperations<K, V> operations) throws DataAccessException {
                operations.watch((K) "healer");
                operations.multi();
                redisTemplate.opsForValue().get("healer");
                return operations.exec();
            }
        });
    }
}
